﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using FikriKibar.Common.Helpers;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.DataAccess.ContextBase;
using FikriKibar.DataAccess.RepositoryBase;
using FikriKibar.Entities.Concrete;

namespace FikriKibar.DataAccess
{
    public class EfMenuHistoryDal : EfEntityRepositoryBase<MenuHistory, FikriKibarDbContext>, IMenuHistoryDal
    {
        protected override MenuHistory AddEntity(MenuHistory entity, FikriKibarDbContext context)
        {
            return context.MenuHistories.Add(entity);
        }

        protected override MenuHistory UpdateEntity(MenuHistory entity, FikriKibarDbContext context)
        {
            var oldEntity = GetEntity(entity, context);
            var newEntity = Mapper.Map(entity, oldEntity);
            context.Entry(oldEntity).CurrentValues.SetValues(newEntity);
            return newEntity;
        }

        protected override List<MenuHistory> GetEntities(FikriKibarDbContext context)
        {
            return context.MenuHistories.ToList();
        }

        protected override List<MenuHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<MenuHistory, bool>> where)
        {
            return context.MenuHistories.Where(where).ToList();
        }

        protected override List<MenuHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<MenuHistory, bool>> where, SortHelper<MenuHistory> sortHelper)
        {
            var query = (IOrderedQueryable<MenuHistory>) context.MenuHistories.Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.ToList();
        }

        protected override List<MenuHistory> FilterEntities(FikriKibarDbContext context, Expression<Func<MenuHistory, bool>> where, SortHelper<MenuHistory> sortHelper, int index, int size)
        {
            var query = (IOrderedQueryable<MenuHistory>) context.MenuHistories.Where(where);
            query = sortHelper.GenerateOrderedQuery(query);
            return query.Skip((index - 1) * size).Take(size).ToList();
        }

        protected override MenuHistory GetEntity(MenuHistory entity, FikriKibarDbContext context)
        {
            return context.MenuHistories.FirstOrDefault(e => e.Id == entity.Id);
        }
    }
}
